// pages/my-loans/my-loans.js
const api = require('../../utils/api.js')
const util = require('../../utils/util.js')
const app = getApp()

Page({
    data: {
        activeTab: 'all',
        loans: [],
        stats: {},
        statusText: {
            'pending': '待审批',
            'approved': '借用中',
            'rejected': '已拒绝',
            'returned': '已归还',
            'overdue': '已逾期'
        },
        loading: false,
        showReturnModal: false,
        returnLoanId: '',
        returnAssetName: '',
        conditionOptions: [
            { value: 'good', label: '完好' },
            { value: 'damaged', label: '损坏' }
        ],
        conditionIndex: 0,
        returnRemark: ''
    },

    onLoad() {
        // 检查登录状态
        if (!app.isLoggedIn()) {
            wx.showModal({
                title: '需要登录',
                content: '查看借用记录需要先登录',
                confirmText: '去登录',
                cancelText: '返回',
                success: res => {
                    if (res.confirm) {
                        wx.redirectTo({
                            url: '/pages/login/login'
                        })
                    } else {
                        wx.navigateBack()
                    }
                }
            })
            return
        }

        this.loadLoans()
        this.loadStats()
    },

    // 切换标签
    switchTab(e) {
        const { tab } = e.currentTarget.dataset
        this.setData({ activeTab: tab })
        this.loadLoans()
    },

    // 加载借用记录
    async loadLoans() {
        if (this.data.loading) return

        this.setData({ loading: true })

        try {
            const params = {
                openid: app.globalData.openid,
                page: 1,
                pageSize: 50
            }

            if (this.data.activeTab !== 'all') {
                params.status = this.data.activeTab
            }

            const data = await api.request({
                url: '/my-loans',
                data: params
            })

            // 格式化数据
            const loans = data.list.map(loan => {
                // 格式化时间
                loan.borrow_date = util.formatTime(util.safeDate(loan.borrow_date))
                if (loan.actual_return_date) {
                    loan.actual_return_date = util.formatTime(util.safeDate(loan.actual_return_date))
                }

                // 计算是否逾期
                if (loan.status === 'approved') {
                    const expected = util.safeDate(loan.expected_return_date)
                    const today = new Date()
                    loan.is_overdue = expected < today && (loan.status === 'approved' || loan.status === 'overdue')
                }
                return loan
            })

            this.setData({ loans, loading: false })
        } catch (error) {
            console.error('加载借用记录失败', error)
            wx.showToast({ title: '加载失败', icon: 'none' })
            this.setData({ loading: false })
        }
    },

    // 加载统计
    async loadStats() {
        try {
            const data = await api.request({
                url: '/my-loans',
                data: { openid: app.globalData.openid }
            })

            const stats = {
                total: data.list.length,
                pending: data.list.filter(l => l.status === 'pending').length,
                approved: data.list.filter(l => l.status === 'approved' || l.status === 'overdue').length,
                returned: data.list.filter(l => l.status === 'returned').length
            }

            this.setData({ stats })
        } catch (error) {
            console.error('加载统计失败', error)
        }
    },

    // 归还设备
    returnAsset(e) {
        const { id, name } = e.currentTarget.dataset
        this.setData({
            showReturnModal: true,
            returnLoanId: id,
            returnAssetName: name,
            conditionIndex: 0,
            returnRemark: ''
        })
    },

    // 选择状况
    onConditionChange(e) {
        this.setData({ conditionIndex: parseInt(e.detail.value) })
    },

    // 备注输入
    onRemarkInput(e) {
        this.setData({ returnRemark: e.detail.value })
    },

    // 隐藏弹窗
    hideReturnModal() {
        this.setData({ showReturnModal: false })
    },

    // 停止冒泡
    stopPropagation() { },

    // 确认归还
    async confirmReturn() {
        try {
            wx.showLoading({ title: '处理中...' })

            const condition = this.data.conditionOptions[this.data.conditionIndex].value

            await api.request({
                url: '/asset/loan/return',
                method: 'POST',
                data: {
                    loanId: this.data.returnLoanId,
                    returnCondition: condition,
                    openid: app.globalData.openid
                }
            })

            wx.hideLoading()
            wx.showToast({
                title: '归还成功',
                icon: 'success'
            })

            this.setData({ showReturnModal: false })

            // 刷新列表
            setTimeout(() => {
                this.loadLoans()
                this.loadStats()
            }, 1000)

        } catch (error) {
            wx.hideLoading()
            console.error('归还失败', error)
            wx.showToast({
                title: error.message || '归还失败',
                icon: 'none'
            })
        }
    },

    // 下拉刷新
    onPullDownRefresh() {
        this.loadLoans()
        this.loadStats()
        wx.stopPullDownRefresh()
    }
})
